package com.sn.springboot_netty.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Author fyy
 * @Description
 * @Date 2020/5/28 15:27
 */
public class ImageUtil {

    private static final String imgPath = TemplateWordUtil.class.getResource("/static/alarm_img").getPath();
    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * @Author fyy
     * @Description 下载网络图片到本地目录
     * @param filePath
     * @Date 2020/5/28 15:28
     */
    public static void makeImage( String filePath,String folderPath,String fileName) {
        File file = new File(imgPath+"/"+folderPath);
        if(!file.exists()){
            file.mkdirs();
        }
        InputStream in = null;
        ByteArrayOutputStream outputStream = null;
        FileOutputStream fOutputStream = null;
        try {
            URL url = new URL(filePath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            in = conn.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int len = 0;
            while((len = in.read(buffer)) != -1){
                outputStream.write(buffer,0,len);
            }
            byte[] data = outputStream.toByteArray();
            File imageFile = new File(file + "/" + fileName + filePath.substring(filePath.lastIndexOf(".")));
            fOutputStream = new FileOutputStream(imageFile);
            fOutputStream.write(data);
        } catch (Exception e) {
            logger.error("图片文件下载异常：{}",e.getMessage());
        } finally {
            try {
                if(null!=fOutputStream)fOutputStream.close();
                if(null!=outputStream)outputStream.close();
                if(null!=in)in.close();
            } catch (IOException e) {
                logger.error("图片文件下载流关闭异常：{}",e.getMessage());
            }
        }
    }

}
